package com.mec.web.y2013.m03;

import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.apache.log4j.Logger;

import com.mec.beans.y2012.coreservlet.DBInfoBean;
import com.mec.web.y2013.WebXMLConfig2013;

/**
 * Read the JDBC configuration file and put the config info in applicatinScope;
 * @author MEC
 * @since 2013-03-30
 */
@WebListener("Listens the JDBC configuration for this web-app")
public class JdbcConfigListener implements ServletContextListener {

    /**
     * Default constructor. 
     */
    public JdbcConfigListener() {
    }

	/**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent sce) {
    	ServletContext appContext = sce.getServletContext();
    	String jdbcConfFile = appContext.getInitParameter(WebXMLConfig2013.JDBC_CONF_FILE);
    	try {
			Properties props = new Properties();
			props.load(appContext.getResourceAsStream(jdbcConfFile));
			DBInfoBean dbInfo = new DBInfoBean(
				props.getProperty(WebXMLConfig2013.JDBC_CONF_DB_VENDOR),
				props.getProperty(WebXMLConfig2013.JDBC_CONF_DB_DESCRIPTION),
				props.getProperty(WebXMLConfig2013.JDBC_CONF_DRIVER_CLASS),
				props.getProperty(WebXMLConfig2013.JDBC_CONF_DB_URL),
				props.getProperty(WebXMLConfig2013.JDBC_CONF_USERNAME),
				props.getProperty(WebXMLConfig2013.JDBC_CONF_PASSWORD)
					);
			appContext.setAttribute(WebXMLConfig2013.APP_ATTR_DB_INFO, dbInfo);
		} catch (Exception e) {
			logger.error(e);
		}
    }

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent sce) {
    }
	
    private static final Logger logger = Logger.getLogger(JdbcConfigListener.class);
}
